package com.shequan.common.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;
import java.io.UnsupportedEncodingException;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
 * <P>
 * Copyright 2012 shequaner.
 * 验证码
 * All Rights Reserved.
 * @author Liust
 * @version 1.0, 2012-3-1
 * @see com.shequan.common.controller.VerifyCodeController 
 * @since 1.0
 */
@Controller
@RequestMapping("/code")
public class VerifyCodeController {

	private Random random = new Random();// 随机器
	private final static String SIMPLE_CAPCHA_SESSION_KEY = "verifyCode";// 存放字符串的session名字

	private static char[] captchars = new char[] { '2', '3', '4', '5', '6', '7', '8', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'A',
			'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y' };// 0，1，2易和字母的o，l,z易混淆，不生成,可以生成汉字

	@RequestMapping(value = "/get")
	public void getTmpCode(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		// 修改的信息在此
		int num = 4;// 字符的多少
		int ImageWidth = num * 40;// 图片的宽
		int ImageHeight = 60;// 图片的高
		int line_left = 7;// 从左上到右下的线条个数
		int line_right = 8;// 从右上到左下的线条个数

		int car = captchars.length - 1;
		Font font = getFont();// 获得写的时候的字体

		// 随机写字母或汉字
		String test = "";
		for (int i = 0; i < num; i++) {
			// 1.随机得到num个字母或数字
			test += captchars[random.nextInt(car) + 1];
			font = new Font("Fixedsys", Font.PLAIN, 40);
		}

		req.getSession(true).setAttribute(SIMPLE_CAPCHA_SESSION_KEY, test);// 将字符串写入session

		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(resp.getOutputStream());// 得到输出流

		BufferedImage bi = new BufferedImage(ImageWidth, ImageHeight, BufferedImage.TYPE_BYTE_INDEXED);

		Graphics2D graphics = bi.createGraphics();

		Color c = getRandColor(200, 250);
		graphics.setColor(c);// 设置背景色

		graphics.fillRect(0, 0, bi.getWidth(), bi.getHeight());

		graphics.setColor(Color.black);

		graphics.setFont(font);
		graphics.setColor(this.getRandColor());
		graphics.drawString(test, 10, 50);// 将字写到图片上

		TextLayout textTl = new TextLayout(test, new Font("Fixedsys", Font.PLAIN, 20), new FontRenderContext(null, true, false));// 获得字体一样的字，20是字体的大小
		textTl.draw(graphics, 30, 60);// 对字体加投影，第二个是左右相距，越大越远，第三个参数是上下两层相距距离，越大越近

		int w = bi.getWidth();
		int h = bi.getHeight();
		shear(graphics, w, h, c);// 使图片扭曲

		this.drawThickLine(graphics, 0, random.nextInt(ImageHeight) + 1, ImageWidth, random.nextInt(ImageHeight) + 1, 4, getRandColor(100, 200));// 加一道线

		// 从左上到右下加上多道干扰线
		graphics.setColor(getRandColor(160, 200));// 设置线条的颜色
		for (int i = 0; i < line_left; i++) {
			int x = random.nextInt(ImageWidth - 1);
			int y = random.nextInt(ImageHeight - 1);
			int xl = random.nextInt(6) + 1;
			int yl = random.nextInt(12) + 1;
			graphics.drawLine(x, y, x + xl + 40, y + yl + 20);
		}
		// 从右上到左下加多道干扰线
		for (int i = 0; i < line_right; i++) {
			int x = random.nextInt(ImageWidth - 1);
			int y = random.nextInt(ImageHeight - 1);
			int xl = random.nextInt(12) + 1;
			int yl = random.nextInt(6) + 1;
			graphics.drawLine(x, y, x - xl + 40, y - yl);
		}
		// 添加噪点
		float yawpRate = 0.012f;// 噪声率
		int area = (int) (yawpRate * w * h);
		for (int i = 0; i < area; i++) {
			int x = random.nextInt(w);
			int y = random.nextInt(h);
			int rgb = getRandomIntColor();
			bi.setRGB(x, y, rgb);
		}

		// 设置图片类型
		resp.setContentType("image/jpg");
		// 写出
		encoder.encode(bi);
	}

	// 添加噪点的方法
	private int getRandomIntColor() {
		int[] rgb = this.getRandomRgb();
		int color = 0;
		for (int c : rgb) {
			color = color << 8;
			color = color | c;
		}
		return color;
	}

	private int[] getRandomRgb() {
		int[] rgb = new int[3];
		for (int i = 0; i < 3; i++) {
			rgb[i] = random.nextInt(255);
		}
		return rgb;
	}

	// 扭曲方法
	private void shear(Graphics g, int w1, int h1, Color color) {
		shearX(g, w1, h1, color);
		shearY(g, w1, h1, color);
	}

	private void shearX(Graphics g, int w1, int h1, Color color) {

		int period = random.nextInt(2);

		boolean borderGap = true;
		int frames = 1;
		int phase = random.nextInt(2);

		for (int i = 0; i < h1; i++) {
			double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
			g.copyArea(0, i, w1, 1, (int) d, 0);
			if (borderGap) {
				g.setColor(color);
				g.drawLine((int) d, i, 0, i);
				g.drawLine((int) d + w1, i, w1, i);
			}
		}

	}

	private void shearY(Graphics g, int w1, int h1, Color color) {

		int period = random.nextInt(40) + 10; // 50;

		boolean borderGap = true;
		int frames = 20;
		int phase = 7;
		for (int i = 0; i < w1; i++) {
			double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
			g.copyArea(i, 0, 1, h1, 0, (int) d);
			if (borderGap) {
				g.setColor(color);
				g.drawLine(i, (int) d, i, 0);
				g.drawLine(i, (int) d + h1, i, h1);
			}

		}
	}

	// 画一道粗线的方法
	private void drawThickLine(Graphics g, int x1, int y1, int x2, int y2, int thickness, Color c) {

		// The thick line is in fact a filled polygon
		g.setColor(c);
		int dX = x2 - x1;
		int dY = y2 - y1;
		// line length
		double lineLength = Math.sqrt(dX * dX + dY * dY);

		double scale = (double) (thickness) / (2 * lineLength);

		// The x and y increments from an endpoint needed to create a
		// rectangle...
		double ddx = -scale * (double) dY;
		double ddy = scale * (double) dX;
		ddx += (ddx > 0) ? 0.5 : -0.5;
		ddy += (ddy > 0) ? 0.5 : -0.5;
		int dx = (int) ddx;
		int dy = (int) ddy;

		// Now we can compute the corner points...
		int xPoints[] = new int[4];
		int yPoints[] = new int[4];

		xPoints[0] = x1 + dx;
		yPoints[0] = y1 + dy;
		xPoints[1] = x1 - dx;
		yPoints[1] = y1 - dy;
		xPoints[2] = x2 - dx;
		yPoints[2] = y2 - dy;
		xPoints[3] = x2 + dx;
		yPoints[3] = y2 + dy;

		g.fillPolygon(xPoints, yPoints, 4);
	}

	// 随机得到一个汉字的方法
	protected char getRandomChar() {
		final int minFirstByte = 176;
		final int maxFirstByte = 215;
		final int minSecondByte = 161;
		final int maxSecondByte = 249;

		byte[] b = new byte[2];
		b[0] = (byte) (getRandomIntBetween(minFirstByte, maxFirstByte));
		b[1] = (byte) (getRandomIntBetween(minSecondByte, maxSecondByte));
		try {
			String s = new String(b, "gb2312");
			assert s.length() == 1;
			return s.charAt(0);
		} catch (UnsupportedEncodingException uee) {
			// 重试
			return getRandomChar();
		}
	}

	/**
	 * 获取两个整数之间的某个随机数，包含较小的整数，不包含较大的整数
	 */
	private int getRandomIntBetween(int first, int second) {
		if (second < first) {
			int tmp = first;
			first = second;
			second = tmp;
		}
		return random.nextInt(second - first) + first;
	}

	/**
	 * 产生随机字体
	 */
	private Font getFont() {
		Random random = new Random();
		Font font[] = new Font[5];
		font[0] = new Font("Ravie", Font.PLAIN, 40);
		font[1] = new Font("Antique Olive Compact", Font.PLAIN, 40);
		font[2] = new Font("Fixedsys", Font.PLAIN, 40);
		font[3] = new Font("Wide Latin", Font.PLAIN, 40);
		font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, 40);
		return font[random.nextInt(5)];
	}

	/**
	 * 随机产生定义的颜色
	 */
	private Color getRandColor() {
		Random random = new Random();
		Color color[] = new Color[10];
		color[0] = new Color(32, 158, 25);
		color[1] = new Color(218, 42, 19);
		color[2] = new Color(31, 75, 208);
		return color[random.nextInt(3)];
	}

	private Color getRandColor(int fc, int bc) {
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}
}
